package com.hnxxxy.utils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hnxxxy.mapper.UserOperationMapper;
import com.hnxxxy.pojo.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;

/**
 * @author：张浩东
 * @Phone：15096207164
 * @QQ：1367048164
 * @E-mail：1367048164@qq.com
 * @date:2020-05-15 17:48
 */
@Service
public class Communal {
    private static final Logger log = LogManager.getLogger(Communal.class);


    @Autowired
    UserOperationMapper userOperationMapper;

    private String user;

    public String getUser() {
        return this.user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    private String ip;

    public String getIp() { return ip; }

    public void setIp(String ip) { this.ip = ip; }

    Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

    public String resultMap(Object status, Object message) {
        resultMap.put("status", status);
        resultMap.put("message", message);
        return JSONObject.fromObject(resultMap).toString();
    }

    public String md5(String password, String salt1) {
        //加密方式
        String hashAlgorithmName = "MD5";
        //密码原值
        Object crdentials = password;
        //以账号作为盐值
        ByteSource salt = ByteSource.Util.bytes(salt1);
        //加密1000次
        int hashIterations = 1000;
        //加密后的密码
        return new SimpleHash(hashAlgorithmName, crdentials, salt, hashIterations).toHex();
    }

    public String sjyz(Map<String, String> map) {
        // 数据验证
        for (Map.Entry<String, String> m : map.entrySet()) {
            if (m.getValue() == null) {
                String x = dataVerify(m.getKey());
                log.debug(x + "数据验证失败");
                return resultMap(500, x);
            }
        }
        return null;
    }

    public String dataVerify(String key) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        resultMap.put("a_id", "社团id不能为空!");
        resultMap.put("a_name", "社团名字不能为空!");
        resultMap.put("username", "学号不为空!");

        String x = null;
        for (Map.Entry<String, String> m : map.entrySet()) {
            if (m.getKey().equals(key)) {
                x = m.getValue();
            }
        }
        return x;
    }

    public String RUD(int returnedValue) {
        if (returnedValue > 0) {
            return resultMap(200, "操作成功");
        } else {
            return resultMap(500, "操作失败");
        }
    }

    /**
     * 单文件删除
     * @param fileName 文件名字
     * @return 成功：true ，失败：false
     */
    public boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * 单图片上传操作
     * @param files 图片流
     * @param request
     * @return 成功：图片的名字，失败：null
     * @throws IOException
     */
    public String path(MultipartFile files, HttpServletRequest request) throws IOException {
        String path1 = request.getSession().getServletContext().getRealPath("/");
        String path2 = StringUtils.substringBefore(path1, "target") + "\\static\\images";

        File file = new File(path2);
        if (!file.exists()) {
            file.mkdirs();
        }

        if (files != null) {
            String filename = files.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().toUpperCase();
            // 去掉-符号
            String salt = uuid.toString().replace("-", "");
            filename = salt + "_" + filename;
            files.transferTo(new File(file, filename));
            log.debug(filename + "上传成功");
            return filename;
        } else{
            return null;
        }
    }

    /**
     * 查询的数据分页封装成json
     * @param page 页数
     * @param limt 行数
     * @param list 要分页的数据
     * @return 封装好的Layui风格的Json数据
     */
    public String runterListJson(int page,int limt,List<?> list){
        PageInfo<?> pageInfo = pageInfo(page, limt, list);
        Layui layui = new Layui();
        layui.Layui(0,"ok",pageInfo.getTotal(),pageInfo.getList());
        return JSONObject.fromObject(layui).toString();
    }

    /**
     * 分页插件操作
     * @param page 页数
     * @param limt 行数
     * @param list 要分页的数据
     * @return 分页插件的对象
     */
    public PageInfo<?> pageInfo(int page,int limt,List<?> list){
        PageHelper.startPage(page,limt);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
